<template>
    <section class="content">
        <el-col :span="24">
            <el-button type="primary" class="button-add" @click="useradd = true"><i class="el-icon-edit"></i>添加用户</el-button>
        </el-col>
         <el-col :span="24">
            <el-table :data="tableData" stripe highlight-current-row  class="table">
                <el-table-column type="index" width="60"></el-table-column>
                    <el-table-column prop="userIdentity.name" label="角色"> </el-table-column>
                    <el-table-column prop="id" label="用户ID"> </el-table-column>
                    <el-table-column prop="name" label="姓名"> </el-table-column>
                    <el-table-column prop="phoneNum" label="手机号"> </el-table-column>
                    <el-table-column prop="email" label="邮件"> </el-table-column>
                    <el-table-column prop="operation" label="操作" > 
                    <template slot-scope="scope">
                        <el-button  @click="deleteRow(scope.$index,scope.row)" type="text" size="small">移除</el-button>
                        <el-button   type="text"  @click="handleEdit(scope.$index, scope.row)" size="small">编辑</el-button>
                        <el-button  v-if="userIdentityId === 1"  type="text"  @click="passwordEdit(scope.$index, scope.row)" size="small">修改密码</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="block">
                <span class="show-pager">显示总数</span>
                <el-pagination
                  @current-change="handleCurrentChange"
                  @pre-click="handlePreClick"
                  @next-click="handleNextClick"
                  :current-page.sync="currentPage"
                  :page-size="10"
                  layout="total, prev, pager, next"
                  :total= "totalRecord" >
                </el-pagination>
              </div>
        </el-col>

        <el-dialog title="添加成员" :visible.sync="useradd" :modal='false'>
             <el-form :model="form"  :rules="rules">
                  <el-form-item :label-width="formLabelWidth">
                       <span style=" color: red">tips:新用户默认密码为“111111”,可以使用手机号登录</span>
                  </el-form-item>
                  <el-form-item :label-width="formLabelWidth" label="用户手机号：" prop="phone">
                    <el-input v-model="form.phone" placeholder="请输入手机号" class="input-w-480"></el-input>
                  </el-form-item>
                  <el-form-item :label-width="formLabelWidth" label="姓名：">
                    <el-input v-model="form.name" placeholder="请输入用户姓名" class="input-w-480"></el-input>
                  </el-form-item>
                  <el-form-item label="身份：" :label-width="formLabelWidth">
                    <el-select v-model="form.identity" clearable placeholder="请选择" @change="selectKey">
                        <el-option v-for="item in formoptions" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                  </el-form-item>
                   <el-form-item :label-width="formLabelWidth" label="邮件：" prop="email">
                    <el-input type="email" v-model="form.email" placeholder="请输入邮件" class="input-w-480"></el-input>
                  </el-form-item>
                  <el-form-item :label-width="formLabelWidth" label="密码：" prop="password">
                    <el-input type="password" v-model="form.password" placeholder="请输入密码" class="input-w-480"></el-input>
                    <br/><span style=" color: red">tips:密码不填为“111111”</span>
                  </el-form-item>
                  <el-form-item :label-width="formLabelWidth" label="确认密码：" prop="password_confirm">
                    <el-input type="password" v-model="form.password_confirm" placeholder="请输入确认密码" class="input-w-480"></el-input>
                  </el-form-item>
             </el-form>
                <div slot="footer" class="">
                     <el-button @click="useradd = false">取消</el-button>
                    <el-button type="primary" v-if="submit12" @click="submit">确定</el-button>
                </div>
        </el-dialog>
	
	  <el-dialog title="编辑成员" :visible.sync="userEdit" :modal='false'>
             <el-form :model="edit"  :rules="rules">
                  <el-form-item :label-width="formLabelWidth">
                      <span style=" color: red">tips:新用户默认密码为“111111”,可以使用手机号登录</span>
                  </el-form-item>
                  <el-form-item :label-width="formLabelWidth" label="用户手机号：" prop="phone">
                    <el-input v-model="edit.phone" :placeholder="form.phone" class="input-w-480"></el-input>
                  </el-form-item>
                  <el-form-item :label-width="formLabelWidth" label="姓名：">
                    <el-input v-model="edit.name" :placeholder="form.name" class="input-w-480"></el-input>
                  </el-form-item>
                  <el-form-item label="身份：" :label-width="formLabelWidth">
                    <el-select v-model="edit.identity" clearable :placeholder="formoptions.name" @change="selectKey">
                        <el-option v-for="item in formoptions" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                  </el-form-item>
                   <el-form-item :label-width="formLabelWidth" label="邮件：" prop="email">
                    <el-input type="email" v-model="edit.email" :placeholder="form.email" class="input-w-480"></el-input>
                  </el-form-item>
             </el-form>
                <div slot="footer" class="">
                     <el-button @click="userEdit = false">取消</el-button>
                    <el-button type="primary" @click="submitEdit">确定</el-button>
                </div>
      </el-dialog>
      <!-- 超级管理员修改用户密码 -->
      <el-dialog title="修改密码"  :visible.sync="passwordEditAdmin" :modal='false'>
        <el-form :model="editPasswordAdmin" :rules="rulesPassAdmin" >
            <el-form-item label="新密码" prop="newpass" :label-width="formLabelWidth">
                    <el-input v-model="editPasswordAdmin.newpass" placeholder="请输入新密码" id="newkey" type="password"></el-input>
               </el-form-item>
               <el-form-item label="重复新密码" prop="checknewpass" :label-width="formLabelWidth">
              <el-input v-model="editPasswordAdmin.checknewpass" placeholder="请再次输入新密码" id='newkey1' type="password"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="">
                     <el-button @click="passwordEditAdmin = false">取消</el-button>
                    <el-button type="primary" v-if="buttonAdminPawd"  @click="submitEditPasswordAdmin">确定</el-button>
                </div>
      </el-dialog>
      
     <!-- 超级管理员修改自己密码 -->
      <el-dialog title="修改密码"  :visible.sync="passwordEditMe" :modal='false'>
        <el-form :model="editPasswordMe" :rules="rulesPassMe">
            <el-form-item label="原密码" prop="oldPassword" :label-width="formLabelWidth">
               <el-input v-model="editPasswordMe.oldPassword" placeholder="请输入原密码" type="password"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword" :label-width="formLabelWidth">
                    <el-input v-model="editPasswordMe.newPassword" placeholder="请输入新密码"  type="password"></el-input>
               </el-form-item>
               <el-form-item label="重复新密码" prop="checknewpass1" :label-width="formLabelWidth">
              <el-input v-model="editPasswordMe.checknewpass1" placeholder="请再次输入新密码" type="password"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="">
                     <el-button @click="passwordEditMe = false">取消</el-button>
                    <el-button type="primary" v-if="buttonMePawd"  @click="submitEditPasswordMe">确定</el-button>
                </div>
      </el-dialog>

    </section>
</template>
<script>
export default {
  data() {
    var validatePass = (rule, value, callback) => {            
          if (this.form.password === value) {
            this.submit12 = true
          } else if (value !== this.form.password) {
            callback(new Error('两次输入密码不一致!'));
            this.submit12 = false
          } else {
            callback();
            this.submit12 = true
          }
    };
    var validatePass1 = (rule,value,callback) =>{
      if (this.form.password_confirm===value) {
            this.submit12 = true
     }else if(this.form.password_confirm != ''||this.form.password_confirm !=value){
        callback(new Error('请再次输入密码'));
        this.submit12 = false
      }else  if(value === ''|| this.form.password_confirm != ''){
        this.submit12 = true
      }else{
         callback();
         this.submit12 = true
      }
    };

    var validatePass2 = (rule, value, callback) => {
           if (value === "") {
            callback(new Error("请再次输入密码"));
          } else if (value !== this.editPasswordAdmin.newpass) {
           callback(new Error("两次输入密码不一致!"));
            } else {
            this.buttonAdminPawd=true
            callback();
          }
    };
    var validatePass4 = (rule, value, callback) => {
      if(this.editPasswordMe.oldPassword === ""){
            callback(new Error("请输入原密码"));
          }else {
            callback();
          }
    };
    var validatePass3 = (rule, value, callback) => {
          if (value === "") {
            callback(new Error("请再次输入密码"));
          } else if (value !== this.editPasswordMe.newPassword) {
           callback(new Error("两次输入密码不一致!"));
           this.buttonMePawd = false
            } else {
            this.buttonMePawd = true
            callback();
          }
    };
    return {
      projectId: null,
      formLabelWidth: "120px",
      submit12:true,
      useradd: false,
      userEdit: false,
      passwordEditAdmin:false,
      buttonAdminPawd:false,
      passwordEditMe:false,
      buttonMePawd:false,
      tableData: [],
      totalRecord: 0,
      totalPage: 0,
      currentPage: 1,
      id: "",
      token:'',
      userId:'',
      role: "",
      formoptions: [],
      userIdentity: {
        id: ""
      },
      userIdentityId:'',
      form: {
        id: "",
        phone: "",
        name: "",
        email: "",
        password:'',
        password_confirm:'',
      },
      edit:{
         id: "",
        phone: "",
        name: "",
        email: ""
      },
      // 超级用户from
      editPasswordAdmin:{
        newpass:'',
        checknewpass:''
      },
      // 修改自身密码
      editPasswordMe:{
        oldPassword:'',
        newPassword:'',
        checknewpass1:'',
      },
      rules:{
        phone:[
          {required: true,message: "请输入电话号码"},
          {pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,message: "手机格式不对"}
        ],
        email:[
          {required: true,message: "请输入邮箱地址"},
          {pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/,message: "邮箱地址格式不对"}
        ],
        password:[
          {validator: validatePass1, trigger: 'blur' }
        ],
        password_confirm:[
          {validator: validatePass, trigger: 'blur' }
        ]
      },

      rulesPassAdmin:{
        checknewpass: [ { required: true, validator: validatePass2, trigger: "blur" } ]
      },

      rulesPassMe:{
        oldPassword:[
          {required: true, validator: validatePass4, trigger: "blur"}
        ],
        newPassword:[
          {required: true, message:"请输入新密码"}
        ],
        checknewpass1:[
          {required: true, validator: validatePass3, trigger: "blur"}
        ],
      },
    };
    
  },
  methods: {
    handleEdit(index, row) {
      (this.edit.id = row.id),
        (this.edit.phone = row.phoneNum),
        (this.edit.name = row.name),
        (this.edit.email = row.email),
        (this.formoptions.name = row.userIdentity.name),
        (this.userEdit = true);
    },
    //编辑
    submitEdit() {
      let data = {
        id: this.edit.id,
        phoneNum: this.edit.phone,
        name: this.edit.name,
        email: this.edit.email,
        "userIdentity.id": this.edit.identity
      };
      console.log(data)
      this.userModel
        .userEdit(data)
        .then(res => {
          if (res.status === 200) {
            this.$message({
              type: "success",
              message: res.msg
            });
            this.userEdit = false
            this.handleCurrentChange(event)
          } else {
            this.$message({
              type: "info",
              message: res.msg
            });
          }
        })
        .catch(err => {
          console.log(err.massage);
        });
    },
    deleteRow(index, rows) {
      if(rows.id !=this.userId){
        this.$confirm("是否要删除?", "提示", {
          confirmButtonText: "删除",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          var userid = rows.id;
          this.tableData.splice(index, 1);
            this.userModel
              .userDelete(userid)
              .then(res => {
                this.$message({
                  type: "success",
                  message: res.data
                });
              })
              .catch(err => {
                console.log(err.message);
              });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
      }else{
         this.$confirm("不能删除正在登录用户", "提示", {
          type: "warning"
        })
      }
    },
    selectKey(id) {
      this.id = id;
      let obj = {};
      obj = this.formoptions.find(item => {
        return item.id === id;
        this.id = obj.id;
      });
    },
    //添加用户
    submit() {
      //判断是否传入密码
      if(this.form.password === ''&&this.form.password_confirm === ''){
        let data = {
        phoneNum: this.form.phone,
        name: this.form.name,
        email: this.form.email,
        "userIdentity.id": this.form.identity
        };
        this.userModel
          .userAdd(data)
          .then(res => {
            if (res.status === 200) {
              this.$message({
                type: "success",
                message: "用户添加成功"
              });
              this.handleCurrentChange(event)
              this.useradd = false;
            } else {
              this.$message({
                type: "info",
                message: res.msg
              });
            }
          })
          .catch(err => {
            console.log(err.massage);
          });
      }else if(this.form.password === this.form.password_confirm){
        let data = {
        phoneNum: this.form.phone,
        name: this.form.name,
        email: this.form.email,
        password: this.form.password,
        "userIdentity.id": this.form.identity
        };
        this.userModel
          .userAdd(data)
          .then(res => {
            if (res.status === 200) {
              this.$message({
                type: "success",
                message: "用户添加成功,请牢记密码"
              });
              this.handleCurrentChange(event)
              this.useradd = false;
            } else {
              this.$message({
                type: "info",
                message: res.msg
              });
            }
          })
          .catch(err => {
            console.log(err.massage);
          });
      }
    },
    //修改密码

    passwordEdit(index,row){
      //判断是否修改自己密码
      if(row.id === this.userId){
        this.passwordEditMe = true
      }else{
        this.passwordEditAdmin = true;
      }
      this.editPasswordAdmin.id = row.id;
    },
    //超级管理员更改其他用户密码
    submitEditPasswordAdmin(){
        let dataPwd={
          type:0,
          id: this.editPasswordAdmin.id,
          password: this.editPasswordAdmin.newpass,
        }
        this.userModel.editPassword(dataPwd).then(res=>{
            if(res.status === 200){
            this.passwordEditAdmin=false
            this.$message({
                  type: "success",
                  message: res.msg
                });
          }else{
            this.$message({
                  type: "info",
                  message: res.msg
                });
          }
        }).catch(err =>{
          console.log(err)
        })
    },
    //超级管理员更改自己密码
    submitEditPasswordMe(){
      let dataPwd={
          type:1,
          oldPassword: this.editPasswordMe.oldPassword,
          newPassword: this.editPasswordMe.newPassword,
        }
        this.userModel.editPassword(dataPwd).then(res=>{
           if(res.status === 200){
            this.passwordEditMe=false
            this.$message({
                  type: "success",
                  message: res.msg
                });
          }else{
            this.$message({
                  type: "info",
                  message: res.msg
                });
          }
        }).catch(err =>{
          console.log(err)
        })
    },
    handleCurrentChange(event) {
      var data = {
        projectId: this.projectId,
        currentPage: this.currentPage,
        pageSize: 10
      }
      this.projectModel
        .getUserByPrj(data)
        .then(res => {
          this.tableData = res.data.list;
        })
        .catch(err => {
          console.log(err.message);
        });
    },

    handlePreClick(event) {
      if (this.currentPage != 1) {
        this.currentPage--;
      }
    },
    handleNextClick(event) {
      if (this.currentPage != this.totalPage) {
        this.currentPage++;
      }
    }
  },
  mounted() {
    this.projectId = this.$route.query.projectId;
    this.token = sessionStorage.getItem("token")
    this.userModel.userToken(this.token).then(res => {
      this.userId=res.data.id
      this.userIdentityId=res.data.userIdentity.id
      }).catch(err => {
        console.log(err.message)
      })

    this.userModel
      .getAllIdentity()
      .then(res => {
        this.formoptions = res.data;
      })
      .catch(err => {
        console.log(err.message);
      });
    var data = {
      projectId: this.projectId,
      currentPage: 1,
      pageSize: 10
    }
    this.projectModel
      .getUserByPrj(data)
      .then(res => {
        this.totalRecord = res.data.totalRecord;
        this.totalPage = res.data.totalPage;
        this.tableData = res.data.list;
      })
      .catch(err => {
        console.log(err.message);
      });
  }
};
</script>
<style scoped>
.content {
  padding-top: 10px;
  overflow-y: auto;
}
</style>

<style >
.content {
  padding-top: 20px;
  background-color: #ffffff;
  width: 100%;
  height: 100%;
}
.button-add {
  margin-left: 20px;
}
.table {
  margin-top: 10px;
  margin-left: 10px;
  width: auto;
  margin-right: 10px;
}
.show-pager {
  font-size: 14px;
  color: #8492a6;
  line-height: 44px;
  margin-left: 20px;
}
.show-pager + .el-pagination {
  float: right;
  width: 70%;
  margin: 5px 20px 0 0;
}
</style>